package com.chookss.mine.personal.collection;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.tiku.SearchSubjectDetailActivity;
import com.chookss.tiku.entity.Subject;
import com.chookss.tiku.util.TiKuUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.components.ImmersionFragment;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

@SuppressLint("ValidFragment")
public class CollectionSubjectFragment extends CollectionBaseFragment {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.llBg)
    LinearLayout llBg;

    private View emptyView;
    private TextView tvNone;//空布局;
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private CollectionAdapter adapter;
    private List<Subject> list = new ArrayList<>();
    private boolean isManage = false;//是否是管理模式

    public CollectionSubjectFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.common_srlview_center_fragment, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        //注册接受
        EventBus.getDefault().register(this);
        return view;
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    private void init() {
        rv.setBackgroundColor(getResources().getColor(R.color.white));
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new CollectionAdapter(R.layout.item_collection_subject, getActivity(), list);
        ((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
        rv.setAdapter(adapter);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        emptyView = LayoutInflater.from(mContext).inflate(R.layout.layout_common_empty, rv, false);
        ViewGroup.LayoutParams layoutParams=emptyView.getLayoutParams();
        layoutParams.height=Utils.getScreenHeight(mContext)-Utils.dip2px(mContext, (float) 100.5);
        emptyView.setLayoutParams(layoutParams);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        tvNone.setText("暂无题目收藏");
    }

    @Override
    public void onLazyAfterView() {
        super.onLazyAfterView();
        srlView.autoRefresh();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize);
        String url = Urls.getCollectSubject;
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<Subject>>>() {
        }.getType(), null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<Subject>>() {
            @Override
            public void onSuccess(List<Subject> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                int oldIndex = list.size();
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(oldIndex, data.size());
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                    }
                }
                setSize(list.size());
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });

    }

    class CollectionAdapter extends BaseQuickAdapter<Subject, BaseViewHolderEx> {
        private Context context;

        public CollectionAdapter(int layoutResId, Context context, @Nullable List<Subject> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, Subject item) {
            RelativeLayout rlChoice = helper.getView(R.id.rlChoice);
            ImageView item_choice = helper.getView(R.id.item_choice);
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvType = helper.getView(R.id.tvType);
            TextView tvTime = helper.getView(R.id.tvTime);
            TextView tvName = helper.getView(R.id.tvName);
            View line = helper.getView(R.id.line);
            tvTitle.setText(item.subjectContent);
            if (isManage) {
                rlChoice.setVisibility(View.VISIBLE);
                if (item.isChoice) {
                    item_choice.setBackgroundResource(R.drawable.icon_fx_select);
                } else {
                    item_choice.setBackgroundResource(R.drawable.shape_circle_b5b5b5_20);
                }
            } else {
                rlChoice.setVisibility(View.GONE);
            }
            if (helper.getItemPosition() == list.size() - 1) {
                line.setVisibility(View.GONE);
            } else {
                line.setVisibility(View.VISIBLE);
            }
            tvTime.setText(Utils.getAccurateDate(item.createTime));
            tvType.setText(TiKuUtils.subjectTypeName(item.subjectTypeCode));
            if(Utils.isNull(item.employeeName)){
                tvName.setVisibility(View.GONE);
            }else{
                tvName.setVisibility(View.VISIBLE);
                tvName.setText("提供人：" + item.employeeName);
            }

            rlChoice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.isChoice) {
                        item.isChoice = false;
                        item_choice.setBackgroundResource(R.drawable.shape_circle_b5b5b5_20);
                        EventBus.getDefault().post(new MyEvent("Collection_Subtract"));
                    } else {
                        item.isChoice = true;
                        item_choice.setBackgroundResource(R.drawable.icon_fx_select);
                        EventBus.getDefault().post(new MyEvent("Collection_Add"));
                    }
                }
            });

            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, SearchSubjectDetailActivity.class);
                    intent.putExtra("watermark", "2");
                    intent.putExtra("subject", item);
                    mContext.startActivity(intent);
                }
            });

        }
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("subjectCode")&&map.containsKey("collectFlag")) {
                srlView.autoRefresh();
            }
        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
                if (msg.equals("Collection_Edit")) {
                    isManage = true;
                    adapter.notifyDataSetChanged();
                } else if (msg.equals("Collection_Save")) {
                    isManage = false;
                    adapter.notifyDataSetChanged();
                } else if (msg.equals("Collection_Delete")) {
                    String collectId = "";
                    int index = 0;
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).isChoice) {
                            if (Utils.isNull(collectId)) {
                                collectId = list.get(i).subjectCode;
                            } else {
                                collectId = collectId + "," + list.get(i).subjectCode;
                            }
                            index = i;
                        }
                    }
                    collectVedio(collectId, index);
                }
            }
        }
    }

    private void collectVedio(String collectId, int index) {
        if (Utils.isNull(collectId)) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("collectId", collectId);
        map.put("collectStatus", "0");// 0 取消 1 收藏
        map.put("collectType", "1");  //收藏类型 0 收藏视频 1 收藏题目
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<String>>() {
        }.getType(), null, Urls.toCollect, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (srlView != null) {
                    if (collectId.contains(",")) {
                        srlView.autoRefresh();
                    } else {
                        list.remove(index);
                        adapter.notifyItemRemoved(index);
                        adapter.notifyItemRangeChanged(index, list.size() - index);
                        if (list.size() == 0) {
                            isEnd = true;
                            adapter.setEmptyView(emptyView);
                        }
                        setSize(list.size());
                    }

                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }

    @Override
    public void initImmersionBar() {

    }
}
